package vendalenger.debvi.jfx;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;

import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.BorderPane;
import javafx.util.Callback;

public class VD_FileTreeView extends BorderPane {
	
	ArrayList<TreeItem<String>> leaves;
	File base;
	TreeView<String> view;
	
	/**
	 * Create a new FileTreeView
	 * @param rootFile 
	 * @param rootIcon
	 */
	@SuppressWarnings("rawtypes")
	public VD_FileTreeView(File rootFile, Node rootIcon) {
		base = rootFile;
		TreeItem<String> root = new TreeItem<String> (rootFile.getName(), rootIcon);
        root.setExpanded(true);
        leaves = new ArrayList<TreeItem<String>>();
        addFiles(rootFile, root);
        view = new TreeView<String>(root);
        view.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem>() {
			@Override
			public void changed(ObservableValue<? extends TreeItem> observable, TreeItem oldValue, TreeItem newValue) {
				ArrayList<String> rp = new ArrayList<String>();
				TreeItem on;
				on = newValue;
				String path = "";
				while (on.getParent() != null) { /* add up the treeitem's parents until null is reached */
					rp.add(on.getValue().toString());
					on = on.getParent();
				}
				Collections.reverse(rp); /* then reverse it */
				for (String string : rp) {
					path += "/" + string;
				}
				System.out.println(base.getAbsolutePath() + path);
			}
        });
        view.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
        setCenter(view);
	}
	
	public void getSelectedFile() {
		
	}
	
	public void setOnOpen(final EventHandler<? super MouseEvent> set) {
		view.setCellFactory(new Callback<TreeView<String>, TreeCell<String>>() {
			@Override
			public TreeCell<String> call(TreeView<String> param) {
				return new TreeCell<String>() {
					protected void updateItem(String item, boolean empty) {
						super.updateItem(item, empty);
						if (!isEmpty()) {
							setGraphic(new Label(item, getTreeItem().getGraphic()));
							this.setOnMouseClicked(set);
						}else{
							setGraphic(new Label(" "));
						}
					}
				};
			}
		});
	}
	
	public static void addFiles(File dir, TreeItem<String> in) {
		for (File f : dir.listFiles()) {
			TreeItem<String> item = new TreeItem<String>(f.getName());
			if (f.isDirectory()) {
				addFiles(f, item);
			}
			in.getChildren().add(item);
		}
	}
}
